/**
 * 
 */
package fr.fermeManager.application.views.models;

import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;

import fr.fermeManager.library.model.beans.Transaction;
import fr.fermeManager.library.model.beans.TypeTransaction;

/**
 * @author Mo
 *
 */
public class ModelComboBoxTypeTransaction extends DefaultComboBoxModel<TypeTransaction> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private List<TypeTransaction> listeTypesTransac;
	
	private Transaction currentTransaction = new Transaction();
	
	public ModelComboBoxTypeTransaction() {
		super();
	}
	
	public ModelComboBoxTypeTransaction(List<TypeTransaction> listeTypesTransacParam) {
		super();
		listeTypesTransac = new ArrayList<TypeTransaction>();
		TypeTransaction rootElement = null;
		for (TypeTransaction typeTransactionTmp : listeTypesTransacParam) {
			if(typeTransactionTmp.getIdParent() == null){
				rootElement = typeTransactionTmp;
				listeTypesTransac.add(rootElement);
				break;
			}
		}
		ajouterFils(listeTypesTransacParam,listeTypesTransac,rootElement);
	}
	
	private void ajouterFils(List<TypeTransaction> listeSource, List<TypeTransaction> listeTarget, TypeTransaction rootElement) {
		for (TypeTransaction typeTransactionTmp : listeSource) {
			if((typeTransactionTmp.getIdParent()!=null) && (typeTransactionTmp.getIdParent() == rootElement.getId())){
				listeTarget.add(typeTransactionTmp);
				ajouterFils(listeSource,listeTarget,typeTransactionTmp);
			}
		}
	}

	public ModelComboBoxTypeTransaction(List<TypeTransaction> listeTypesTransacParam,Transaction transacSelecParam) {
		super();
		listeTypesTransac = new ArrayList<TypeTransaction>();
		TypeTransaction rootElement = null;
		for (TypeTransaction typeTransactionTmp : listeTypesTransacParam) {
			if(typeTransactionTmp.getIdParent() == null){
				rootElement = typeTransactionTmp;
				listeTypesTransac.add(rootElement);
				break;
			}
		}
		ajouterFils(listeTypesTransacParam,listeTypesTransac,rootElement);
		currentTransaction = transacSelecParam;
	}

	@Override
	public int getSize() {
		return listeTypesTransac.size();
	}

	@Override
	public TypeTransaction getElementAt(int index) {
		return listeTypesTransac.get(index);
	}

	@Override
	public int getIndexOf(Object anObject) {
		return listeTypesTransac.indexOf(anObject);
	}

	@Override
	public void setSelectedItem(Object anObject) {
		currentTransaction.setTypeTransaction((TypeTransaction) anObject);
	}

	@Override
	public Object getSelectedItem() {
		if(currentTransaction==null){
			return null;
		}
		return currentTransaction.getTypeTransaction();
	}
}
